package com.xu.blog_after_end.web.admin;

import com.xu.blog_after_end.po.User;
import com.xu.blog_after_end.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/admin")  // 全局路径
public class LongController {
    @Autowired  // 自动注入
    private UserService userService;
    @GetMapping  // 访问全局admin路径
    public String loginPage(){  // 登录页面
        return "admin/login";  // 返回登录页面
    }
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes){  // post请求获取登录信息
        User user = userService.checkUser(username, password);  // 检查用户名密码是否正确
        if(user != null){  // 登录成功
            user.setPassword(null);
            session.setAttribute("user", user);
            return "admin/index";
        }else{  // 登录失败
            attributes.addFlashAttribute("message", "用户名和密码错误");
            return "redirect:/admin";  // 重定向返回登录页面
        }
    }
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
